package com.sailing.xjpb.common.thread;

import com.sailing.xjpb.common.exception.BusinessException;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.Supplier;

/**
 * 任务执行器-使用jdk1.8以前默认异步执行线程收集结果
 *
 * @param <T> 任务执行完成返回结果类型
 */
@Data
public final class TaskRunnerV1<T> {

    private final List<Future<T>> taskList;

    private final ExecutorService threadPools;


    public TaskRunnerV1(ExecutorService threadPools) {
        this.threadPools = threadPools;
        this.taskList = new ArrayList<>();
    }


    public void doExecute(Supplier<T> supplier) {
        Future<T> submitted = threadPools.submit(supplier::get);
        taskList.add(submitted);
    }

    public List<T> collect() {
        List<T> rsList = new ArrayList<>(taskList.size());
        for (Future<T> rs : taskList) {
            try {
                rsList.add(rs.get());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw BusinessException.businessError("异步任务执行出错：线程中断！", e);
            } catch (Exception e) {
                throw BusinessException.businessError("异步任务执行出错", e);
            }
        }
        return rsList;
    }

}
